import validHtml from 'ngtemplate!html!../../../tpls/dialog/valid.dialog.html';
import teamForCircleDistHtml from 'ngtemplate!html!../../../tpls/realtime/team.circle.dist.tpl.html';

class RealtimeListPersonalController {
    constructor($rootScope, $scope, $cookieStore, $timeout, $state, $filter, ngDialog, tableService, dialogService, ScoreService, getRaceDetail, getCourseList, iRunner, getGroupList){

        var vm = this;

        vm.$rootScope    = $rootScope;
        vm.$cookieStore  = $cookieStore;
        vm.$timeout      = $timeout;
        vm.$state        = $state;
        vm.$filter       = $filter;
        vm.ngDialog      = ngDialog;
        vm.tableService  = tableService;
        vm.dialogService = dialogService;
        vm.ScoreService  = ScoreService;
        vm.iRunner       = iRunner;


        //赛事详情
        vm.raceDetail = getRaceDetail;
        //科目列表详情
        vm.courseList = getCourseList.data;
        // 科目不为空, 默认选中第一个
        if (vm.courseList.length>0) {
            vm.course = vm.courseList[0];
        }

        //保存当前科目名称
        vm.crouseState = {};
        //保存当前页面数据
        vm.realtimeData = [];

        //搜索后的过滤状态
        vm.searchState = {
            race_name: vm.raceDetail.data.disp_name,
            course_name: '',
            courseId: '',
            type: '',
            sex: '',
            teamName: '',
            realtimeData: []
        }

        /**
         * 监听科目变化
         * @param  {[type]} angular.bind(vm, ()            [description]
         * @param  {[type]} (newValue,       oldValue      [description]
         * @return {[type]}                  [description]
         */
        $scope.$watch(angular.bind(vm, () => vm.course), (newValue, oldValue) => {

            //保存当前科目名称
            vm.crouseState = newValue;

            //清空过滤条件
            vm.sex = '';
            vm.teamname = '';

            console.log(newValue);

            // 查看是否从详情页面跳转
            if (vm.$rootScope.realltimeteamback == 1) {
                vm.$rootScope.realltimeteamback == 0;

                //选择科目
                angular.forEach(vm.courseList, function(data,index){
                    if (data.course_id == vm.$rootScope.searchState.courseId) {
                        vm.course = vm.courseList[index];
                        return;
                    }
                });

                //填充搜索条件
                vm.sex = vm.$rootScope.searchState.sex;
                vm.teamname = vm.$rootScope.searchState.teamName;

                //搜索数据
                vm.searchTableData(vm.$rootScope.searchState.type, vm.$rootScope.searchState.courseId, vm.$rootScope.searchState.sex, vm.$rootScope.searchState.teamName)
            } else {
                //搜索数据
                vm.searchTableData(newValue.course_type, vm.course.course_id, '', '')
            }

        });


        /**
         * 发布成绩
         */
        vm.publish = function() {

            // 模态框显示文本
            $rootScope.common = {
                text : '是否发布成绩'
            }

            vm.ngDialog.open({
                template: validHtml,
                className: 'ngdialog-theme-default ngdialog-alert',
                scope: $scope
            });


            $rootScope.submitDelForm = (isValid) => {
                if (!isValid) {
                    vm.dialogService.error();
                }

                if (isValid) {

                    // 关闭模态框
                    vm.ngDialog.close();
                    // 显示进度条
                    $rootScope.progressBar = true;


                    var status = '', start = '', total = '';
                    // 完结时间
                    var dueTime = '--';

                    // 重新计算所有成绩（调用后台接口）
                    var importStart = (status, start, total) => {
                        vm.ScoreService.getRealtimeScorePublish(vm.$cookieStore.get('access_token'), vm.$state.params.race_id + '&start=' + start)
                        .then( data => {
                            console.log(data);
                            if (data.code == 0) {

                                status = data.data.status;
                                start = data.data.current;
                                total = data.data.total;

                                //设置进度条百分比
                                $rootScope.progress =  parseInt(start/total*100) + '%';
                                //总条数
                                $rootScope.total = total;
                                //完结条数
                                $rootScope.begin = start;
                                // 完结时间（耗时）
                                $rootScope.dueTime = parseInt((total-start)/4) + '秒';


                                if (status == 'continue') {
                                    importStart(status, start, total);                        
                                } else if (status == 'done') {
                                    $rootScope.progressBar = false;
                                    return;
                                }

                            } else {
                                vm.dialogService.error(data.message);
                            }

                        }, error => {
                            vm.dialogService.error("计算失败");
                            console.log('error')
                        });
                    }

                    importStart(status, start, total);

                }
                console.log('重新计算所有成绩')
                return false;
            }
        }

        /**
         * 重新计算所有成绩
         * @return {[type]} [description]
         */
        vm.recalc = function() {

            // 模态框显示文本
            $rootScope.common = {
                text : '您要重新计算所有选手的成绩吗？这将耗费数分钟或更长时间'
            }

            vm.ngDialog.open({
                template: validHtml,
                className: 'ngdialog-theme-default ngdialog-alert',
                scope: $scope
            });

 

            $rootScope.submitDelForm = (isValid) => {
                if (!isValid) {
                    vm.dialogService.error();
                }

                if (isValid) {

                    // 关闭模态框
                    vm.ngDialog.close();
                    // 显示进度条
                    $rootScope.progressBar = true;


                    var status = '', start = '', total = '';
                    // 完结时间
                    var dueTime = '--';

                    // 重新计算所有成绩（调用后台接口）
                    var importStart = (status, start, total) => {
                        vm.ScoreService.getRealtimeScorecalc(vm.$cookieStore.get('access_token'), vm.$state.params.race_id + '&start=' + start)
                        .then( data => {
                            console.log(data);
                            if (data.code == 0) {

                                status = data.data.status;
                                start = data.data.current;
                                total = data.data.total;

                                //设置进度条百分比
                                $rootScope.progress =  parseInt(start/total*100) + '%';
                                //总条数
                                $rootScope.total = total;
                                //完结条数
                                $rootScope.begin = start;
                                // 完结时间（耗时）
                                $rootScope.dueTime = parseInt((total-start)/4) + '秒';


                                if (status == 'continue') {
                                    importStart(status, start, total);
                                } else if (status == 'done') {
                                    $rootScope.progressBar = false;
                                    return;
                                }

                            } else {
                                vm.dialogService.error(data.message);
                            }

                        }, error => {
                            vm.dialogService.error("计算失败");
                            console.log('error')
                        });
                    }

                    importStart(status, start, total);

                }
                console.log('重新计算所有成绩')
                return false;
            }   
        }

        /**
         * 打印实时页面成绩
         * @return {[type]} [description]
         */
        vm.print = function() {

            //科目名称
            vm.searchState.course_name = vm.crouseState.course_name,
            //科目赛制
            vm.searchState.type = vm.crouseState.course_type,
            //表格数据
            vm.searchState.realtimeData = vm.reamtimeTeamlist,

            //存储数据到Local storage
            localStorage.setItem('realtimeDataForPrint', JSON.stringify(vm.searchState));
            console.log(vm.searchState);
            //打开打印页面
            window.open("tpls/realtime/printforteam.html");
        }


        /**
         * 下载成绩
         * @return {[type]} [description]
         */
        vm.download = function() {
            //下载成绩链接
            vm.window = window.open("/dashboard/realtime/download?course_id=" + vm.course.course_id + "&access-token=" + this.$cookieStore.get('access_token'));                 
        }

        /**
         * [searchTableData description]
         * @return {[type]} [description]
         */
        vm.searchTableData = function (courseType, courseId, sex, teamname) {

            //科目id
            vm.searchState.courseId = courseId
            //保存搜索赛制状态
            vm.searchState.type = courseType;
            //保存搜索性别状态
            vm.searchState.sex = sex;
            //保存搜索团队状态
            vm.searchState.teamName = teamname;

            //清空模板数据
            vm.$timeout( () => { vm.teamTpl = ''; }, 0);

            // 单程定距的场合
            if (courseType == 'oneway') {
            	// 个人实时成绩单程定距模板
            	vm.$timeout( () => { vm.teamTpl = teamForCircleDistHtml; }, 0);
            	vm.$timeout( () => { vm.getCircleDistData(courseId, sex, teamname); }, 0);   
                //vm.dialogService.error("该赛制本页面未提供该赛制查询功能。");
                // vm.$timeout( () => { vm.ngDialog.close();vm.$state.go('dashboard.race.realtimelist'); }, 1500);

            } else if (courseType == 'circle') {

                // 个人实时成绩单程定距模板
                vm.$timeout( () => { vm.teamTpl = teamForCircleDistHtml; }, 0);
                //请求数据（个人实时成绩绕圈定距）
                vm.$timeout( () => { vm.getCircleDistData(courseId, sex, teamname); }, 0);   

            } else {
            	// 个人实时成绩单程定距模板
            	vm.$timeout( () => { vm.teamTpl = teamForCircleDistHtml; }, 0);
            	vm.$timeout( () => { vm.getCircleDistData(courseId, sex, teamname); }, 0);   
            	//vm.dialogService.error("该赛制本页面未提供该赛制查询功能-----其他。");
                // vm.$timeout( () => { vm.ngDialog.close();vm.$state.go('dashboard.race.realtimelist'); }, 2000);
            }

        }

        /**
         * [getCircleDistData 团队实时成绩（绕圈定距）]
         * @param  {[type]} courseId [description]
         * @param  {[type]} sex      [description]
         * @param  {[type]} teamname [description]
         * @return {[type]}          [description]
         */
        vm.getCircleDistData = function(courseId, sex, teamname) {
            sex  = sex || '';
            teamname = teamname || '';

            //清空表格数据
            vm.reamtimeTeamlist = [];

            //加载中
            vm.lodingFlag = true;
            // 隐藏没有搜索到数据
            vm.reamtimeTeamlistFlag = false

            //调用后台接口，团队绕圈定距
            vm.ScoreService.getRealtimeCircleDistData(vm.$cookieStore.get('access_token'), vm.$state.params.race_id + '&course_id=' + courseId + '&search[team_gender]=' + sex + '&search[team_name]=' + teamname)
            .then(function(data) {
                //取得数据（调用后台接口，团队绕圈定距）
                vm.reamtimeTeamlist = data.data;
                //加载中消失
                vm.lodingFlag = false;
                //显示没有搜索到数据
                if (vm.reamtimeTeamlist.length != 0) {
                    vm.reamtimeTeamlistFlag = false;
                } else {
                    vm.reamtimeTeamlistFlag = true;
                }
                console.log(data)
            }, function(data) {
                //加载中消失
                vm.lodingFlag = false;
                console.log('error')
            });

        }

        /**
         * [click 点击进入详情页面]
         * @return {[type]} [description]
         */
        vm.click = function(course_id, team_name) {
            //存储当前搜索条件
            $rootScope.searchState = vm.searchState;
        }
    }

}

RealtimeListPersonalController.$inject = ['$rootScope', '$scope', '$cookieStore', '$timeout', '$state', '$filter', 'ngDialog', 'tableService', 'dialogService', 'ScoreService', 'getRaceDetail', 'getCourseList', 'iRunner', 'getGroupList']; 

export default RealtimeListPersonalController;